package com.caocaog.market.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caocaog.market.entity.ShopBasic;
import com.caocaog.market.entity.ShopChannel;
import com.caocaog.market.entity.ShopChannelshop;
import com.caocaog.market.service.IShopBasicService;
import com.caocaog.market.service.IShopChannelService;
import com.caocaog.market.service.IShopChannelshopService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 频道店铺关联表
 *
 * @author jeecg-boot
 * @date 2021-11-23
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(value = "shopChannelshop", tags="频道店铺关联表")
@RequestMapping("/shop/shopChannelshop")
public class ShopChannelshopController extends JeecgController<ShopChannelshop, IShopChannelshopService> {
	@Autowired
	private IShopChannelshopService shopChannelshopService;
	@Autowired
	private IShopBasicService shopBasicService;
	@Autowired
	private CommonAPI commonAPI;
	@Autowired
	private IShopChannelService shopChannelService;
	
	/**
	 * 分页列表查询
	 *
	 * @param shopChannelshop
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "频道店铺关联表-分页列表查询")
	@ApiOperation(value="频道店铺关联表-分页列表查询", notes="频道店铺关联表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(ShopChannelshop shopChannelshop,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ShopChannelshop> queryWrapper = QueryGenerator.initQueryWrapper(shopChannelshop, req.getParameterMap());
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if (oConvertUtils.isNotEmpty(loginUser.getUserType()) && 1!= loginUser.getUserType()) {
			LambdaQueryWrapper<ShopBasic> shopQuery = new LambdaQueryWrapper<>();
			if (2== loginUser.getUserType()) {

				//分站
				String siteId = loginUser.getSiteId();
				//获取商户ids
				List<String> merchantIds = commonAPI.findMerchantForSite(siteId);
				//获取门店
				if (oConvertUtils.listIsNotEmpty(merchantIds)){

					shopQuery.in(ShopBasic::getMerchantId,merchantIds);
					List<String> shopIds = shopBasicService.list(shopQuery).stream().map(ShopBasic::getId).collect(Collectors.toList());
					if (oConvertUtils.listIsNotEmpty(shopIds)){
						queryWrapper.in("shop_id",shopIds);
					}

				}

			}else if (3== loginUser.getUserType()){
				//商户
				String merchantId = loginUser.getMerchantId();
				//获取门店
				//todo 首先获取选择的门店
				// 首先获取选择的门店
				if (oConvertUtils.isNotEmpty(loginUser.getCurrentSelectedShopId()) ){
					queryWrapper.in("shop_id", loginUser.getCurrentSelectedShopId());
				}else {
					shopQuery.eq(ShopBasic::getMerchantId,merchantId);
					List<String> shopIds = shopBasicService.list(shopQuery).stream().map(ShopBasic::getId).collect(Collectors.toList());
					if (oConvertUtils.listIsNotEmpty(shopIds)){
						queryWrapper.in("shop_id",shopIds);
					}else {
						//当前无门店
						return Result.error("您还没有自己的门店,请先添加自己的门店哟~");
					}
				}

			}
		}
		Page<ShopChannelshop> page = new Page<ShopChannelshop>(pageNo, pageSize);
		IPage<ShopChannelshop> pageList = shopChannelshopService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param shopChannelshop
	 * @return
	 */
	@AutoLog(value = "频道店铺关联表-添加")
	@ApiOperation(value="频道店铺关联表-添加", notes="频道店铺关联表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody ShopChannelshop shopChannelshop) {
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if (StringUtils.isBlank(loginUser.getCurrentSelectedShopId()))
			throw new JeecgBootException("用户暂未绑定门店, realName-> " + loginUser.getRealname());
		shopChannelshop.setShopId(loginUser.getCurrentSelectedShopId());
		String[] ids = shopChannelshop.getChannelId().split(",");
		List<ShopChannelshop> shopChannelshops = new ArrayList<>();
		for (String id : ids){
			//check 只能选择二级的
			// 如果该店铺已有该频道 跳过
			ShopChannel shopChannel = shopChannelService.getById(id);
			if ("0".equals(shopChannel.getParentId())){
				return Result.error("请选择二级频道哟~");
			}
			ShopChannelshop check = shopChannelshopService.getOne(new QueryWrapper<ShopChannelshop>()
					.eq("channel_id",id)
					.eq("shop_id",shopChannelshop.getShopId()));
			if (oConvertUtils.isNotEmpty(check)){
				continue;
			}
			ShopChannelshop channelshop = new ShopChannelshop();
			channelshop.setChannelId(id);
			channelshop.setShopId(shopChannelshop.getShopId());
			shopChannelshops.add(channelshop);
		}
		shopChannelshopService.saveBatch(shopChannelshops);
		return Result.OK("添加成功！",true);
	}
	
	/**
	 *  编辑
	 *
	 * @param shopChannelshop
	 * @return
	 */
	@AutoLog(value = "频道店铺关联表-编辑")
	@ApiOperation(value="频道店铺关联表-编辑", notes="频道店铺关联表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody ShopChannelshop shopChannelshop) {

		String[] ids = shopChannelshop.getChannelId().split(",");
		List<ShopChannelshop> shopChannelshops = new ArrayList<>();
		for (String id : ids){
			ShopChannel shopChannel = shopChannelService.getById(id);
			if ("0".equals(shopChannel.getParentId())){
				return Result.error("请选择二级频道哟~");
			}
			//check 如果该店铺已有该频道 跳过
			ShopChannelshop check = shopChannelshopService.getOne(new QueryWrapper<ShopChannelshop>()
					.eq("channel_id",id)
					.eq("shop_id",shopChannelshop.getShopId()));
			if (oConvertUtils.isNotEmpty(check)){
				continue;
			}
			ShopChannelshop channelshop = new ShopChannelshop();
			channelshop.setChannelId(id);
			channelshop.setShopId(shopChannelshop.getShopId());
			shopChannelshops.add(channelshop);
		}
		shopChannelshopService.updateBatchById(shopChannelshops);
		return Result.OK("编辑成功!",true);
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "频道店铺关联表-通过id删除")
	@ApiOperation(value="频道店铺关联表-通过id删除", notes="频道店铺关联表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		shopChannelshopService.removeById(id);
		return Result.OK("删除成功!",true);
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "频道店铺关联表-批量删除")
	@ApiOperation(value="频道店铺关联表-批量删除", notes="频道店铺关联表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.shopChannelshopService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!",true);
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "频道店铺关联表-通过id查询")
	@ApiOperation(value="频道店铺关联表-通过id查询", notes="频道店铺关联表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		ShopChannelshop shopChannelshop = shopChannelshopService.getById(id);
		if(shopChannelshop==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(shopChannelshop);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param shopChannelshop
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ShopChannelshop shopChannelshop) {
        return super.exportXls(request, shopChannelshop, ShopChannelshop.class, "频道店铺关联表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ShopChannelshop.class);
    }

}
